package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat

/**
 *
 * @author xrm
 * @use 获取业务信息
 *
 *
 */
public class GetBusinessHistory implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(GetBusinessHistory.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 1;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        long startTime = System.currentTimeMillis();

        JSONObject result = new JSONObject();
        String callPram = "";
        String oJson = "";

        try {
            //获取客户端传参
            String r_custname = Util.filterForObject(request.getParameter("customername")); //获取客户姓名
            String r_seatno = Util.filterForObject(request.getParameter("seatno")); //获取物业号
            String r_customerid = Util.filterForObject(request.getParameter("customerid")); //客户编号
            String r_custidno = Util.filterForObject(request.getParameter("idno")); //获取身份证号

            //传参处理
            callPram = "调用入参:" + r_custname + " | " + r_seatno + " | " + r_customerid + " | " + r_custidno
            log.debug(callPram);

            //列表接口调用
            if (r_custname.equals("") && r_seatno.equals("") && r_custidno.equals("") && r_customerid.equals("")) {
                result.put("code", "-1");
                result.put("msg", "未传递参数！");
                oJson = result.toString();

            } else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("customername", r_custname);
                map.put("seatno", r_seatno);
                map.put("idno", r_custidno);
                map.put("customerid", r_customerid);
                map.put("key", "ca3c64a49d1f11ecbed6d703198897725e7aba55");
                String ASCIIMD5 = KHUtil.ASCIIORDER(map);
                log.debug("接口返回:" + ASCIIMD5);

                oJson = CustHttpPort(eliteBean, ASCIIMD5); //调用接口方法
                log.debug("接口返回:" + oJson);
            }


        } catch (Exception e) {
            log.error("一体化接口-获取租赁合同 Exception:", e)
            result.put("code", "-1");
            result.put("msg", "调用失败！");
            oJson = result.toString();

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "一体化接口-获取租赁合同", "GetBusinessHistory", callPram, oJson, (System.currentTimeMillis() - startTime).toString(), "/");
        }
        return oJson;
    }


/**
 *
 * @use 业务历史接口调用
 * @param eliteBean
 * @param Custname ,Mobile,Idno,Custnameid* @return
 */
    private String CustHttpPort(EliteBean eliteBean, ASCIIMD5) {
        JSONObject result = new JSONObject();
        try {
            //获取接口地址
            String url = KHDBConfig.getAPIURL(eliteBean, "getStoreContractList");

            String postmap = Util.doHttpPost(url, ASCIIMD5.toString(), charset, timeout, enableSSLflag);
            log.debug("接口返回:" + postmap);

            JSONObject obj = JSONObject.fromObject(sortContractData(postmap));
            if (obj.getInt("status") != 200) {
                result.put("code", "-1");
                result.put("msg", "接口调用返回异常");
                return result;
            } else {
                return obj;
            };

        } catch (Exception e) {
            log.error("errormsg:", e)
            result.put("code", "-1");
            result.put("msg", "程序异常");
            return result;
        }
    }

    /**
     * 单一方法实现JSON中data数组的排序功能
     * 入参：原始JSON字符串
     * 出参：排序后的JSON字符串（异常时返回原JSON）
     * 排序规则：按begindate正序（旧→新），相同则按operatortime正序；无效时间（空/不可解析）排最后
     */
    public static String sortContractData(String originalJson) {
        // 定义JSON解析器
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 1. 解析JSON为内部响应对象
            Response response = mapper.readValue(originalJson, Response.class);
            List<Contract> dataList = response.data;
            if (dataList == null || dataList.isEmpty()) {
                return originalJson; // 空数组直接返回
            }

            // 2. 复制原数组避免修改源数据，执行排序
            List<Contract> sortedList = new ArrayList<>(dataList);
            sortedList.sort(new Comparator<Contract>() {

                @Override
                public int compare(Contract a, Contract b) {
                    // 先比较begindate
                    int beginCompare = compareTime(a.begindate, b.begindate);
                    if (beginCompare != 0) {
                        return beginCompare;
                    }
                    // 再比较operatortime
                    return compareTime(a.operatortime, b.operatortime);
                }

                // 比较两个时间字符串的核心逻辑
                private int compareTime(String timeA, String timeB) {
                    boolean aValid = isTimeValid(timeA);
                    boolean bValid = isTimeValid(timeB);

                    // 有效时间在前，无效时间在后
                    if (aValid && !bValid) return -1;
                    if (!aValid && bValid) return 1;
                    // 都无效则视为相等
                    if (!aValid && !bValid) return 0;

                    // 都有效：按正序（旧→新）比较
                    Date dateA = parseTime(timeA);
                    Date dateB = parseTime(timeB);
                    return dateA.compareTo(dateB);
                }

                // 判断时间字符串是否有效（非空且可解析）
                private boolean isTimeValid(String timeStr) {
                    if (timeStr == null || timeStr.trim().isEmpty()) {
                        return false;
                    }
                    try {
                        // 处理字符串中的多空格（替换为单空格）
                        String normalized = timeStr.trim().replaceAll("\\s+", " ");
                        sdf.parse(normalized);
                        return true;
                    } catch (ParseException ignored) {
                        return false;
                    }
                }

                // 解析时间字符串为Date对象（仅处理有效时间）
                private Date parseTime(String timeStr) {
                    try {
                        String normalized = timeStr.trim().replaceAll("\\s+", " ");
                        return sdf.parse(normalized);
                    } catch (ParseException ignored) {
                        return new Date(0); // 理论上不会走到这里（已通过isTimeValid校验）
                    }
                }
            });

            // 3. 替换排序后的数组并返回新JSON
            response.data = sortedList;
            return mapper.writeValueAsString(response);

        } catch (Exception e) {
            log.error("JSON中data数组的排序异常", e);
            // 任何异常都返回原JSON
            return originalJson;
        }
    }

    // 内部类：映射JSON外层结构
    private static class Response {
        @JsonProperty("data")
        List<Contract> data;
        @JsonProperty("message")
        String message;
        @JsonProperty("status")
        int status;
        @JsonProperty("timestamp")
        long timestamp;
    }

    // 内部类：映射data数组中的元素
    private static class Contract {
        @JsonProperty("begindate")
        String begindate;
        @JsonProperty("operatortime")
        String operatortime;
        // 其他字段无需定义（Jackson会忽略未定义字段，不影响解析）
    }

}








